import Conf from '../config/index'
//redis.js
import Redis from 'ioredis' //导入模块

const redisClient = new Redis(Conf.redis)
class Store {
    constructor(key, options) {
        this.redis = redisClient;
        this.key = key || 'prefix-';
        this.options = {
            ...options,
        }
    }

    // 获取 token
    async get(tk) {
        try {
            let res = JSON.parse(await this.redis.get(this.key + tk));
            if (!res) return null
            if (res.t * 1 !== 0 && (+new Date) > res.t * 1 + res.s * 1) {
                await this.delete(tk);
                return null;
            }
            return res.v;
        } catch (err) {
            console.error('Token Store:get Error'.red, err);
            return null;
        }
    }

    // 设置 token
    async set(tk, val, timeout = 0) { //timeout为过期天数 1，2，3，一天，两天，三天。。
        timeout = 3600 * 24 * (timeout || 0)
        try {
            return await this.redis.set(this.key + tk, JSON.stringify({
                v: val,
                t: timeout,
                s: (+new Date)
            }));;
        } catch (err) {
            console.error('Token Store:set Error'.red, err);
            return null;
        }
    }
    async keys(name) {
            return this.redis.keys(`*${name}*`)
        }
        // 销毁 token
    async delete(tk) {
        try {
            return await this.redis.del(this.key + tk);;
        } catch (err) {
            console.error('Token Store:destroy Error'.red, err);
            return null;
        }
    }
}

export default Store;